package com.you07.learn.exception;

import com.you07.learn.utils.ErrorCode;
import com.you07.learn.utils.Result;
import com.you07.learn.utils.ResultMessage;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName: GlobalExceptionHandler
 * @Author: chenguo
 * @Data: 2019年06月18日 18时19分
 * @Description:
 * @Company: 成都灵奇空间软件
 * @Version: 1.0
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public ResultMessage<?> exceptionHandler(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return Result.error(ex.getErrorCode());
        } else if (e instanceof BindException) {
            BindException ex = (BindException) e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(ErrorCode.ERROR);
        } else {
            return Result.error(ErrorCode.ERROR);
        }
    }
}
